/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-7-11 下午2:36 Created by sky
 */
package com.jade.modules.message.sms.comm;

import java.io.IOException;
import java.io.OutputStream;

import com.jade.framework.base.lang.OctetString;
import org.apache.commons.lang3.StringUtils;

public class DataOutputStream
        extends java.io.DataOutputStream
{
    public static final byte[] FILL_BYTES = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    public DataOutputStream(OutputStream output)
    {
        super(output);
    }

    public int writeString(OctetString str)
            throws IOException
    {
        if (str == null || str.length() == 0) {
            return 0;
        }
        str.writeTo(this);
        return str.length();
    }

    public int writeString(OctetString str, int len)
            throws IOException
    {
        int strLen = writeString(str);
        if (strLen < len) {
            fill(len - strLen);
        }
        return len;
    }

    /**
     * 写出字符串
     *
     * @param str
     */
    public int writeString(String str)
            throws IOException
    {
        if (StringUtils.isBlank(str)) {
            return 0;
        }

        byte[] bytes = str.getBytes();
        write(bytes);
        return bytes.length;
    }

    /**
     * 写出字符串
     *
     * @param str
     * @param len
     */
    public int writeString(String str, int len)
            throws IOException
    {
        int strLen = writeString(str);
        if (strLen < len) {
            fill(len - strLen);
        }
        return len;
    }


    /**
     * 输出字符串
     *
     * @param str
     */
    public void writeCString(String str)
            throws IOException
    {
        if (str != null) {
            byte[] bytes = str.getBytes();
            write(bytes);
        }
        write(0);
    }

    /**
     * 用0来填充
     *
     * @param len 长度
     * @throws java.io.IOException
     */
    public void fill(int len)
            throws IOException
    {
        int l = len;
        while (l > 0) {
            if (l <= FILL_BYTES.length) {
                write(FILL_BYTES, 0, l);
                break;
            }
            else {
                write(FILL_BYTES);
                l -= FILL_BYTES.length;
            }
        }
    }

    /** Write unsigned int. */
    public void writeUnsignedInt(long l)
            throws IOException
    {
        out.write((int) (l >>> 24) & 0xFF);
        out.write((int) (l >>> 16) & 0xFF);
        out.write((int) (l >>> 8) & 0xFF);
        out.write((int) (l >>> 0) & 0xFF);
    }
}
